﻿using Combat;
using PrimeTween;
using UnityEngine;

namespace Visual
{
    [RequireComponent(typeof(Health))]
    public class FlashOnHit : MonoBehaviour
    {
        [SerializeField] private SpriteRenderer spriteRenderer;
        [SerializeField] private float flashDuration = 0.1f;
        [SerializeField] private float recoverDuration = 0.2f;
        
        private Health _health;
        
        private Color _defaultColor;
        private Tween _tween;


        private void Awake()
        {
            _health = GetComponent<Health>();
            
            _defaultColor = spriteRenderer.color;
            _health.Hit += Health_Hit;

            PrimeTweenConfig.warnEndValueEqualsCurrent = false;
        }

        private void Health_Hit(Vector2 _)
        {
            _tween.Stop();
            
            Sequence.Create()
                .Group(Tween.Scale(spriteRenderer.transform, 0.9f, flashDuration))
                .Chain(Tween.Color(spriteRenderer, Color.white, flashDuration))
                .Chain(Tween.Color(spriteRenderer, _defaultColor, recoverDuration))
                .Group(Tween.Scale(spriteRenderer.transform, 1f, recoverDuration));
        }
    }
}